package com.example._9_springmvc.xzy.controller;

import com.example._9_springmvc.xzy.aop.LoginLogAnno;
import com.example._9_springmvc.xzy.pojo.LoginLog;
import com.example._9_springmvc.xzy.service.LoginLogService;
import com.example._9_springmvc.xzy.service.impl.LoginLogServiceImpl;
import com.example._9_springmvc.xzy.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.UUID;

@Controller
public class UserController {
    private UserServiceImpl userService;
    private LoginLogServiceImpl loginLogService;

    @RequestMapping(value = "/index")
    public String loginPage() {
        return "login";
    }

    @LoginLogAnno
    @RequestMapping(value = "/loginCheck")
    public ModelAndView loginCheck(HttpServletRequest request) throws SQLException, ClassNotFoundException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        userService = (UserServiceImpl) applicationContext.getBean("userService");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String loginResult = userService.UserLogin(username, password);
        if (loginResult.equals("success")) {
//            return new ModelAndView("main");
            ModelAndView modelAndView = new ModelAndView("main");
            modelAndView.addObject("message", "login succeed!");
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("loginIP", request.getRemoteAddr().toString());
            Long tmp = System.currentTimeMillis();
            request.getSession().setAttribute("loginTime", tmp.toString());
            return modelAndView;
        } else {
            return new ModelAndView("login");
        }
    }

    @RequestMapping(value = "/upload")
    public ModelAndView upLoadCheck(@RequestParam("uploadFiles") MultipartFile[] multipartFiles, HttpServletRequest request) throws IOException {
        String realpath = "D:\\mycode\\java\\IdeaWork\\web-framework-spring\\spring_web\\src\\main\\resources\\uploaded\\users";
        System.out.println("realpath: " + realpath);
        // 获取上传的文件名
        int fileNum = multipartFiles.length;
        boolean allNull = true;
        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile.getBytes().length >= 1) {
                allNull = false;
            }
        }
        if (allNull) {
            ModelAndView modelAndView = new ModelAndView("main");
            modelAndView.addObject("message", "Can not upload empty file!");
            return modelAndView;
        }
        for (MultipartFile multipartFile : multipartFiles) {
            // 获取上传的文件名
            if (multipartFile.getBytes().length < 1)
                continue;
            String fileName = multipartFile.getOriginalFilename();
            fileName = UUID.randomUUID().toString() + "_" + fileName;
            // 根据路径构建文件对象
            // 在构建过程中一定要注意路径问题，最好写成绝对路径
            File uploadFile = new File(realpath, fileName);
            // 判断指定文件夹uploadfiles是否存在，不存在就创建
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            // 上传文件
            multipartFile.transferTo(uploadFile);
        }
        ModelAndView modelAndView = new ModelAndView("main");
        modelAndView.addObject("message", "upload succeed!");
        return modelAndView;

    }

    @RequestMapping(value = "/download")
    public String downloads(@RequestParam String filename, HttpServletResponse response) throws Exception {
        String path = "D:\\mycode\\java\\IdeaWork\\web-framework-spring\\spring_web\\src\\main\\resources\\uploaded\\users";
        String fileName = filename;
        //1、设置response 响应头
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path, fileName);
        //2、 读取文件--输入流
        InputStream input = new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();
        byte[] buff = new byte[1024];
        int index = 0;
        //4、执行 写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "success";
    }

    @RequestMapping(value = "/showinfo")
    public ModelAndView ShowInfo() throws SQLException, ClassNotFoundException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        loginLogService = (LoginLogServiceImpl) applicationContext.getBean("loginLogService");
        ArrayList<LoginLog> loginLogs = loginLogService.LoginLogFindAll();
        ModelAndView modelAndView = new ModelAndView("showInfo");
        modelAndView.addObject("loginInfos", loginLogs);
        return modelAndView;

    }

}
